<?php
namespace frontend\modules\Api\controllers;

use common\models\User;
use common\services\ToolService;
use common\services\UserService;
use Yii;
use yii\base\DynamicModel;
use yii\helpers\ArrayHelper;


/**
 * Class IndexController
 * @package frontend\modules\Api\controllers
 */
class IndexController extends ApiController
{
    /**
     * @throws \yii\base\ExitException
     */
    public function actionIndex()
    {
        return self::successResponse(['info'=>'hello api']);
    }

    /**
     * App内关于我们的展示接口
     * @throws \yii\base\ExitException
     */
    public function actionAboutPage()
    {
        $str = '<img src="https://www.gongsizhang.com/static/images/logo.png"><br /><p>公司账是一款SAAS记账系统，帮您实现智能财务管理，高效支撑经营决策</p><p>官方网站：www.gongsizhang.com</p><p>联系电话：400-888-9975</p>';
        return self::successResponse(['content'=>$str]);
    }

    /**
     * 生成分享图片
     * @throws \yii\base\ExitException
     */
    public function actionDownloadShare()
    {
        $host = Yii::$app->request->hostInfo;
        $imgSrc = $host.'/public/images/share.jpg' ;
        return self::successResponse(['img'=>$imgSrc]);
    }

    /**
     * 用户反馈留言
     * @throws \yii\base\ExitException
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\db\Exception
     */
    public function actionLeaveMessage()
    {
        $form = DynamicModel::validateData([
            'name' => Yii::$app->getRequest()->post('name',''),
            'email' => Yii::$app->getRequest()->post('email',''),
            'phone' => Yii::$app->getRequest()->post('phone',''),
            'subject' => Yii::$app->getRequest()->post('subject',''),
            'content' => Yii::$app->getRequest()->post('content',''),
        ],[
            [['name','phone','content'], 'required'],
        ]);
        if ($form->hasErrors()) {
            return self::failureResponse(500,current($form->getFirstErrors()));
        }
        $formData = ArrayHelper::toArray($form);
        //  操作入库
        Yii::$app->db->createCommand()->insert('guestbook',$formData)->execute();
        // 发送钉钉推送
        $msg = '[通知]有一条新的留言待处理~~'."\n" ;
        $msg .= '姓名: '.$formData['name']."\n" ;
        $msg .= '邮箱: '.$formData['email']."\n" ;
        $msg .= '电话: '.$formData['phone']."\n" ;
        $msg .= '主题: '.$formData['subject']."\n" ;
        $msg .= '留言: '.$formData['content']."\n" ;
        $msg .= '时间: '.date('Y-m-d H:i:s') ;
        ToolService::dingTalkPush($msg,$_SERVER['DINGTALK_SECRET']);
        return self::successResponse();
    }

    /**
     * 自动登录操作（提供给自己测试用）
     * @throws \yii\base\ExitException
     * @throws \yii\base\InvalidConfigException
     */
    public function actionAutoLogin()
    {
        Yii::$app->user->enableSession = true;
        $mobile = Yii::$app->request->get('mobile');
        $user = User::findByUsername($mobile);
        if(!$user) {
            return self::successResponse(['state'=>0]);
        }else{
            Yii::$app->user->login($user,  3600 * 24 * 30 );
            $token  = ToolService::createUuid();
            // token 存入redis
            UserService::storeLoginToken($token,Yii::$app->user->identity->id);
            $retData = [
                'phone' => Yii::$app->user->identity->mobile,
                'username' =>  Yii::$app->user->identity->username,
                'token' => $token
            ];
            return self::successResponse($retData);
        }

    }
}
